//
//  ComposeController.swift
//  Weibo10
//
//  Created by 刘俊 on 15/10/28.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

/// 撰写控制器
class ComposeController: UIViewController {

    /// 图片选择
    private lazy var picturePicker: PicturePickerController = PicturePickerController()
    /// 表情键盘视图
    private lazy var emoticon: SYLJEmoticon = SYLJEmoticon { [weak self](emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
        
    }
    
    // MARK: - 监听方法
    @objc private func close() {
        // 释放键盘
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send() {
        // 1,获取文本内容
        let text = textView.emoticonText
        let image = UIImage(named: "jingtian")
        // 2,发布微博
        NetworkTools.sharedTools.sendStatus(text,image:image) { (result, error) -> () in
            if error != nil {
                print("出错了")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            print(result)
            // 关闭控制器
            self.close()
        }
        
    }
    @objc private func selectEmoticon() {
        print("添加表情")
//        print("\(textView.inputView)")
        // 释放键盘
        textView.resignFirstResponder()
        // 改变键盘样式
        textView.inputView = textView.inputView == nil ? emoticon : nil
        // 激活键盘
        textView.becomeFirstResponder()
    }
    /// 键盘变化处理
    @objc private func keyboardChanged(n: NSNotification) {
        print(n)
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offset = UIScreen.mainScreen().bounds.size.height - rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-offset)
        }
        // 设置动画曲线
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // MARK: - 视图生命周期
    override func loadView() {
        view = UIView()
        setupUI()
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 叫出键盘
        textView.becomeFirstResponder()
    }

    // MARK: - 懒加载控件
    /// 工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    /// 文本视图
    private lazy var textView: UITextView = {
        let textView = UITextView()
        
        textView.tintColor = UIColor.darkGrayColor()
        textView.font = UIFont.systemFontOfSize(18)
//        textView.text = "分享新鲜事..."
        // 始终运行垂直方向拖拽
        textView.alwaysBounceVertical = true
        // 拖拽时释放键盘
        textView.keyboardDismissMode = .OnDrag
        // 设置文本视图的代理
        textView.delegate = self
        
        return textView
    }()
    /// 占位文本框
    private lazy var placeHolderLabel: UILabel = {
        let lable = UILabel(title: "分享新鲜事...", fontSize: 18, color: UIColor.lightGrayColor())
    
        return lable
    }()

}

// MARK: - 文本视图的代理
extension ComposeController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}

// MARK: - 设置界面
private extension ComposeController {
    
    func setupUI() {
        // 1. 设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        // 2. 设置控件
        prepareNavigationBar()
        prepareToolBar()
        prepareTextView()
        preparePicture()
    }
    
    func preparePicture() {
        addChildViewController(picturePicker)
        
        view.addSubview(picturePicker.view)
        picturePicker.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(view.snp_height).multipliedBy(0.6)
        }
    }
    
    func prepareTextView() {
        view.addSubview(textView)
        
        textView.addSubview(placeHolderLabel)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    func prepareToolBar() {
        // 添加控件
        view.addSubview(toolBar)
        // 设置toolbar的背景颜色
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        // 设置布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(49)
        }
        // 设置
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, actionName: dict["actionName"], target: self)
            
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        
    }
    func prepareNavigationBar() {
    
        // 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        // 禁用发送按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 32))
        navigationItem.titleView = titleView
        let titleLable = UILabel(title: "发微博", fontSize: 15)
        let nameLable = UILabel(title: SYLJUserAccountViewModel.sharedUserAccountViewModel.account?.screen_name ?? "", fontSize: 13, color: UIColor.lightGrayColor())
        
        // 添加控件
        titleView.addSubview(titleLable)
        titleView.addSubview(nameLable)
        
        // 设置布局
        titleLable.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLable.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
    }
    
}